package com.hakim.wfb.customer.service.impl;

import com.hakim.wfb.bean.ConsumeRecord;
import com.hakim.wfb.bean.CreditPoint;
import com.hakim.wfb.bean.User;
import com.hakim.wfb.biz.ConsumeRecordBiz;
import com.hakim.wfb.customer.enums.ErrorCodeEnum;
import com.hakim.wfb.customer.params.team.*;
import com.hakim.wfb.customer.params.trans.CreditPointParam;
import com.hakim.wfb.customer.params.trans.GetConsumeRecordParameter;
import com.hakim.wfb.customer.result.team.TeamInvestRecordView;
import com.hakim.wfb.customer.result.team.TeamLevelDetailView;
import com.hakim.wfb.customer.result.team.TeamMemberInfoView;
import com.hakim.wfb.customer.result.team.TeamOutlineView;
import com.hakim.wfb.customer.result.trans.CreditPointView;
import com.hakim.wfb.customer.service.TeamService;
import com.hakim.wfb.dao.CreditPointDao;
import com.hakim.wfb.dao.UserDao;
import com.hkfs.fundamental.api.data.ListResultEx;
import com.hkfs.fundamental.api.data.ObjectResultEx;
import com.hkfs.fundamental.api.data.ResultEx;
import com.hakim.wfb.common.enums.UserActiveTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * Created by walkman on 2017/7/12.
 */
@Service("teamService")
public class TeamServiceImpl implements TeamService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CreditPointDao creditPointDao;

    @Autowired
    private ConsumeRecordBiz consumeRecordBiz;

    /**
     * 获取团队会员列表
     *
     * @param parameter
     * @return
     */
    @Override
    public ListResultEx<TeamMemberInfoView> getTeamMembers(GetTeamMemberParameter parameter) {
        ListResultEx<TeamMemberInfoView> resultEx = new ListResultEx<>();

        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        parameter.setUserOrg(user.getUserOrg());
        List<TeamMemberInfoView> teamMemberInfoViewList = userDao.getTeamMembers(parameter);
        if (teamMemberInfoViewList != null && teamMemberInfoViewList.size() > 0) {
            teamMemberInfoViewList.stream().forEach(member -> {

                GetConsumeRecordParameter getConsumeRecordParameter = new GetConsumeRecordParameter();
                getConsumeRecordParameter.setUserId(member.getUserId());
                List<ConsumeRecord> consumeRecordList = consumeRecordBiz.getUserConsumeRecords(getConsumeRecordParameter);
                //最近投资
                if (consumeRecordList != null && consumeRecordList.size() > 0) {
                    ConsumeRecord latestRecord =
                            consumeRecordList.stream().max(Comparator.comparing(ConsumeRecord::getCrInvestTime)).get();
                    if (latestRecord != null) {
                        member.setInvestingAccount(latestRecord.getCrCustPoint());
                    } else {
                        member.setInvestingAccount(0.0d);
                    }
                } else {
                    member.setInvestingAccount(0.0d);
                }
                member.setTeamMember(userDao.queryTeamMemberCount(member.getUserOrg(), null));
            });
        }
        resultEx.setTotalCount(userDao.countTeamMembers(parameter));
        resultEx.setDataList(teamMemberInfoViewList);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队待激活会员列表
     *
     * @param parameter
     * @return
     */
    @Override
    public ListResultEx<TeamMemberInfoView> getInactiveTeamMembers(GetTeamMemberParameter parameter) {
        ListResultEx<TeamMemberInfoView> resultEx = new ListResultEx<>();
        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        parameter.setActiveStatus(UserActiveTypeEnum.NOTACTIVED.getValue());
        List<TeamMemberInfoView> teamMemberInfoViewList = userDao.getTeamMembers(parameter);
        resultEx.setTotalCount(userDao.countTeamMembers(parameter));
        resultEx.setDataList(teamMemberInfoViewList);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队会员列表
     *
     * @param parameter
     * @return
     */
    @Override
    public ListResultEx<TeamMemberInfoView> getChildren(GetTeamMemberParameter parameter) {

        ListResultEx<TeamMemberInfoView> resultEx = new ListResultEx<>();

        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        List<TeamMemberInfoView> childrenInfoViewList = userDao.getChildren(parameter);
        if (childrenInfoViewList != null && childrenInfoViewList.size() > 0) {
            childrenInfoViewList.stream().forEach(member -> {

                GetConsumeRecordParameter getConsumeRecordParameter = new GetConsumeRecordParameter();
                getConsumeRecordParameter.setUserId(member.getUserId());
                List<ConsumeRecord> consumeRecordList = consumeRecordBiz.getUserConsumeRecords(getConsumeRecordParameter);
                //最近投资
                if (consumeRecordList != null && consumeRecordList.size() > 0) {
                    ConsumeRecord latestRecord =
                            consumeRecordList.stream().max(Comparator.comparing(ConsumeRecord::getCrInvestTime)).get();
                    if (latestRecord != null) {
                        member.setInvestingAccount(latestRecord.getCrCustPoint());
                    } else {
                        member.setInvestingAccount(0.0d);
                    }
                } else {
                    member.setInvestingAccount(0.0d);
                }
                member.setTeamMember(userDao.queryTeamMemberCount(member.getUserOrg(), null));
            });
        }
        resultEx.setTotalCount(userDao.countChildren(parameter));
        resultEx.setDataList(childrenInfoViewList);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队待激活会员列表
     *
     * @param parameter
     * @return
     */
    @Override
    public ListResultEx<TeamMemberInfoView> getInactiveChildren(GetTeamMemberParameter parameter) {
        ListResultEx<TeamMemberInfoView> resultEx = new ListResultEx<>();
        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        parameter.setActiveStatus(UserActiveTypeEnum.NOTACTIVED.getValue());
        List<TeamMemberInfoView> teamMemberInfoViewList = userDao.getChildren(parameter);
        resultEx.setTotalCount(userDao.countChildren(parameter));
        resultEx.setDataList(teamMemberInfoViewList);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队会员信息概要
     *
     * @param parameter
     * @return
     */
    @Override
    public ObjectResultEx<TeamOutlineView> getTeamOutline(GetTeamOutlineParameter parameter) {
        ObjectResultEx<TeamOutlineView> resultEx = new ObjectResultEx<>();

        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        //获取用户可用激活积分
        CreditPoint creditPoint = creditPointDao.getById(user.getTid());
        if (creditPoint == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        TeamOutlineView teamOutlineView = new TeamOutlineView();
        int teamMemberCount = userDao.queryTeamMemberCount(user.getUserOrg(), null);
        int activeMemberCount = userDao.queryTeamMemberCount(user.getUserOrg(), UserActiveTypeEnum.ACTIVED.getValue());
        int inactiveMemberCount = userDao.queryTeamMemberCount(user.getUserOrg(), UserActiveTypeEnum.NOTACTIVED.getValue());

        teamOutlineView.setMemberCount(teamMemberCount);
        teamOutlineView.setActivatableMemberCount(inactiveMemberCount);
        teamOutlineView.setActivedMemberCount(activeMemberCount);
        teamOutlineView.setAvailableActivePoint(creditPoint.getCpActivitPoint());

        resultEx.setDataObject(teamOutlineView);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队等级详情
     *
     * @param parameter
     * @return
     */
    @Override
    public ObjectResultEx<TeamLevelDetailView> getTeamLevelInfo(GetTeamLevelDetailParameter parameter) {

        ObjectResultEx<TeamLevelDetailView> resultEx = new ObjectResultEx<>();

        User user = userDao.getById(parameter.getUserId());
        if (user == null) {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }

        TeamLevelDetailView teamLevelDetailView = new TeamLevelDetailView();
        int teamMemberCount = userDao.queryTeamMemberCount(user.getUserOrg(), null);
        int directRecommendCount = userDao.queryChildMemberCount(user.getTid(), UserActiveTypeEnum.ACTIVED.getValue());
        int investingDirectRecommendCount = userDao.countDirectActivated(user.getTid());

//        Double teamAchieveSum = userDao.queryTeamAchieveSum(user.getUserOrg());
        Double groupAchieveSum = userDao.queryGroupAchieveSum(user.getTid());

        CreditPoint creditPoint = creditPointDao.getById(user.getTid());
        if (creditPoint == null) {
            resultEx.setRetCode(ErrorCodeEnum.CREDIT_POINT_INVALID_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.CREDIT_POINT_INVALID_ERROR.getMessage());
            return resultEx.makeFailedResult();
        }
        teamLevelDetailView.setDirectRecommend(directRecommendCount);
        teamLevelDetailView.setMemberCount(teamMemberCount);
        teamLevelDetailView.setGroupAchieve(groupAchieveSum);
        teamLevelDetailView.setTeamAchieve(creditPoint.getCpTeamPoint());
        teamLevelDetailView.setInvestingDirectRecommend(investingDirectRecommendCount);
        resultEx.setDataObject(teamLevelDetailView);
        return resultEx.makeSuccessResult();
    }

    /**
     * 获取团队会员投资记录列表
     *
     * @param parameter
     * @return
     */
    @Override
    public ListResultEx<TeamInvestRecordView> getTeamInvestRecord(GetTeamInvestRecordParameter parameter) {
        ListResultEx<TeamInvestRecordView> resultEx = new ListResultEx<>();

        return resultEx.makeSuccessResult();
    }

    /**
     * 激活团队成员
     *
     * @param parameter
     * @return
     */
    @Override
    public ResultEx activateMember(ActivateMemberParameter parameter) {
        ResultEx resultEx = new ResultEx();

        return resultEx.makeSuccessResult();
    }

    @Override
    public ResultEx teamAcheivement(String userid) {
        ResultEx rs = new ResultEx();

        try {


            return rs.makeSuccessResult();
        } catch (Exception e) {
            return rs.makeFailedResult("查询失败");
        }
    }

    @Override
    public ListResultEx<CreditPointView> getTeamAchieve(CreditPointParam parameter) {
        ListResultEx<CreditPointView> lrs = new ListResultEx<CreditPointView>();
        try {
            List<CreditPointView> relist = creditPointDao.getTeamAchieve(parameter.getTid());
            lrs.setTotalCount(relist.size());
            lrs.setDataList(relist);
            return lrs.makeSuccessResult();
        } catch (Exception e) {
            return lrs.makeFailedResult("操作失败" + e);
        }
    }

}
